import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../services/api_service.dart';
import '../widgets/common_button.dart';
import '../widgets/common_text_field.dart';
import 'base_page.dart';
import 'login_page.dart';

/// 用户注册页面
/// 包含用户名、手机号、验证码、密码等输入字段
class RegisterPage extends BasePage {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends BasePageState<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _telController = TextEditingController();
  final _codeController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _addressController = TextEditingController();
  final _shopNameController = TextEditingController();
  final _channelController = TextEditingController();
  
  bool _isCodeLoading = false;
  int _countdown = 0;
  
  @override
  void dispose() {
    _usernameController.dispose();
    _telController.dispose();
    _codeController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _addressController.dispose();
    _shopNameController.dispose();
    _channelController.dispose();
    super.dispose();
  }

  @override
  PreferredSizeWidget? buildAppBar(BuildContext context) {
    return AppBar(
      title: const Text('用户注册'),
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios),
        onPressed: () => goBack(),
      ),
    );
  }

  @override
  Widget buildPageContent(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.all(24.w),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 20.h),
            
            // 标题
            Text(
              '创建新账户',
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              '请填写以下信息完成注册',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey[600],
              ),
            ),
            SizedBox(height: 40.h),
            
            // 用户名
            CommonTextField(
              controller: _usernameController,
              labelText: '用户名',
              hintText: '请输入用户名',
              prefixIcon: Icons.person_outline,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入用户名';
                }
                if (value.length < 2) {
                  return '用户名长度不能少于2位';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 手机号
            CommonTextField(
              controller: _telController,
              labelText: '手机号',
              hintText: '请输入手机号',
              prefixIcon: Icons.phone_outlined,
              keyboardType: TextInputType.phone,
              maxLength: 11,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入手机号';
                }
                if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                  return '请输入正确的手机号';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 验证码
            Row(
              children: [
                Expanded(
                  child: CommonTextField(
                    controller: _codeController,
                    labelText: '验证码',
                    hintText: '请输入验证码',
                    prefixIcon: Icons.verified_user_outlined,
                    keyboardType: TextInputType.number,
                    maxLength: 6,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入验证码';
                      }
                      if (value.length != 6) {
                        return '验证码为6位数字';
                      }
                      return null;
                    },
                  ),
                ),
                SizedBox(width: 12.w),
                SizedBox(
                  width: 120.w,
                  height: 48.h,
                  child: ElevatedButton(
                    onPressed: _countdown > 0 ? null : _getVerifyCode,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _countdown > 0 ? Colors.grey[300] : Theme.of(context).primaryColor,
                      foregroundColor: _countdown > 0 ? Colors.grey[600] : Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                    ),
                    child: _isCodeLoading
                        ? SizedBox(
                            width: 16.w,
                            height: 16.w,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                _countdown > 0 ? Colors.grey[600]! : Colors.white,
                              ),
                            ),
                          )
                        : Text(
                            _countdown > 0 ? '${_countdown}s' : '获取验证码',
                            style: TextStyle(fontSize: 14.sp),
                          ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 20.h),
            
            // 密码
            CommonTextField(
              controller: _passwordController,
              labelText: '密码',
              hintText: '请输入密码',
              prefixIcon: Icons.lock_outline,
              obscureText: true,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入密码';
                }
                if (value.length < 6) {
                  return '密码长度不能少于6位';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 确认密码
            CommonTextField(
              controller: _confirmPasswordController,
              labelText: '确认密码',
              hintText: '请再次输入密码',
              prefixIcon: Icons.lock_outline,
              obscureText: true,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请确认密码';
                }
                if (value != _passwordController.text) {
                  return '两次输入的密码不一致';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 地址
            CommonTextField(
              controller: _addressController,
              labelText: '地址',
              hintText: '请输入地址',
              prefixIcon: Icons.location_on_outlined,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入地址';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 店铺名称
            CommonTextField(
              controller: _shopNameController,
              labelText: '店铺名称',
              hintText: '请输入店铺名称',
              prefixIcon: Icons.store_outlined,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入店铺名称';
                }
                return null;
              },
            ),
            SizedBox(height: 20.h),
            
            // 推广渠道
            CommonTextField(
              controller: _channelController,
              labelText: '推广渠道',
              hintText: '请输入推广渠道',
              prefixIcon: Icons.trending_up_outlined,
            ),
            SizedBox(height: 40.h),
            
            // 注册按钮
            CommonButton(
              text: '立即注册',
              onPressed: _register,
              isLoading: isLoading,
              width: double.infinity,
            ),
            SizedBox(height: 20.h),
            
            // 登录链接
            Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '已有账号？',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      goBack();
                    },
                    child: Text(
                      '立即登录',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Theme.of(context).primaryColor,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 获取验证码
  Future<void> _getVerifyCode() async {
    if (_telController.text.isEmpty) {
      showError('请先输入手机号');
      return;
    }
    
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_telController.text)) {
      showError('请输入正确的手机号');
      return;
    }
    
    setState(() {
      _isCodeLoading = true;
    });
    
    try {
      final result = await ApiService.getVerifyCode(_telController.text);
      
      if (result.success) {
        showSuccess('验证码已发送');
        _startCountdown();
      } else {
        showError(result.message);
      }
    } catch (e) {
      showError('网络错误，请稍后重试');
    } finally {
      setState(() {
        _isCodeLoading = false;
      });
    }
  }
  
  /// 开始倒计时
  void _startCountdown() {
    setState(() {
      _countdown = 60;
    });
    
    Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        timer.cancel();
      }
    });
  }
  
  /// 注册
  Future<void> _register() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }
    
    showLoading('注册中...');
    
    try {
      final result = await ApiService.register(
        username: _usernameController.text.trim(),
        tel: _telController.text.trim(),
        password: _passwordController.text,
        confirmPassword: _confirmPasswordController.text,
        verifyCode: _codeController.text.trim(),
        address: _addressController.text.trim(),
        shopName: _shopNameController.text.trim(),
        channel: _channelController.text.trim(),
      );
      
      if (result.success) {
        showSuccess('注册成功，请登录');
        replaceWith(const LoginPage());
      } else {
        showError(result.message);
      }
    } catch (e) {
      showError('网络错误，请稍后重试');
    } finally {
      hideLoading();
    }
  }
}